import csv
import mimetypes
import os.path
from utils.yamltool import BasePath


class CsvReader:

	def __init__(self, file_path=None, title_line=True):
		if file_path is not None:
			self.file_path = os.path.join(BasePath, 'data', file_path)
			self.file_type, _ = mimetypes.guess_type(str(self.file_path))
		else:
			raise Exception("文件未找到!")
		self.title_line = title_line
		self._data = list()

	@property
	def data(self):
		# 处理.xls文件
		if self.file_type == 'text/csv':
			encodings = ['utf-8', 'ISO-8859-1', 'gbk', 'utf-16']  # 常见编码列表
			for encoding in encodings:
				try:
					with open(self.file_path, 'r', encoding='gbk', errors='ignore') as f:
						cdata = csv.reader(f)
						for row in cdata:
							self._data.append(row)
						break
				except UnicodeDecodeError:
					print(f"尝试使用编码 {encoding} 失败")
				raise ValueError("无法使用任何指定的编码读取文件")
			# 数据是否包含表头
			if self.title_line:
				title = self._data[0]
				self._data = [dict(zip(title, self._data[col])) for col in range(1, len(self._data))]
			else:
				self._data = [col for col in self._data]
		else:
			raise Exception(f"不支持的文件格式: {self.file_type}")
		return self._data


if __name__ == '__main__':
	vals = CsvReader('login.csv').data
	for val in vals:
		print(val)
